# -*- coding: utf-8 -*
import pygame  #需要下载
import sys
import time
import random  #随机数

#----- 全局变量
# 窗口大小
SCREEN_X = 600
SCREEN_Y = 600


# 游戏名称
GAME_NAME = '贪吃蛇'
# 背景颜色
# COLOR = (255,255,255)  
COLOR = (0,0,0)

# 速度
TIME = 10

# 蛇
class Snake(object):
	# 初始化各种需要的属性 [开始时默认向右/身体块x5]
	def __init__(self):
		self.dirction = pygame.K_RIGHT
		self.body = []
		for x in range(5):
				self.addnode()
			
	# 无论何时 都在前端增加蛇块
	def addnode(self):
		left,top = (0,0)
		if self.body:
			left,top = (self.body[0].left,self.body[0].top)
		node = pygame.Rect(left,top,25,25)
		if self.dirction == pygame.K_LEFT:
			node.left -= 25
		elif self.dirction == pygame.K_RIGHT:
			node.left += 25
		elif self.dirction == pygame.K_UP:
			node.top -= 25
		elif self.dirction == pygame.K_DOWN:
			node.top += 25
		self.body.insert(0,node)
	# 死亡判断
	def isdead(self):
		# 撞墙
		if self.body[0].x  not in range(SCREEN_X):
			return True
		if self.body[0].y  not in range(SCREEN_Y):
			return True
		# 撞自己
		if self.body[0] in self.body[1:]:
			return True
		return False
	
	# 移动！
	def move(self):
		self.addnode()
		self.delnode()

	# 删除最后一个块
	def delnode(self):
		self.body.pop()

	# 改变方向 但是左右、上下不能被逆向改变
	def changedirection(self,curkey):
		LR = [pygame.K_LEFT,pygame.K_RIGHT]
		UD = [pygame.K_UP,pygame.K_DOWN]
		if curkey in LR+UD:
			if (curkey in LR) and (self.dirction in LR):
				return
			if (curkey in UD) and (self.dirction in UD):
				return
			self.dirction = curkey


# 食物 
class Food:
	def __init__(self):
		# 生成食物
		self.rect = pygame.Rect(-25,0,25,25)

	# 移除
	def remove(self):
		self.rect.x=-25
	
	def set(self):
		if self.rect.x == -25:
			allpos = []
			# 不靠墙太近 25 ~ SCREEN_X-25 之间
			for pos in range(25,SCREEN_X-25,25):
				allpos.append(pos)
			self.rect.left = random.choice(allpos)
			self.rect.top  = random.choice(allpos)
			# print(self.rect)


# 显示文字
def show_text(screen, pos, text, color, font_bold = False, font_size = 25, font_italic = False):   
    #获取系统字体，并设置文字大小  
    cur_font =pygame.font.Font('myfont.ttf', font_size)  
    #设置是否加粗属性  
    cur_font.set_bold(font_bold)  
    #设置是否斜体属性  
    cur_font.set_italic(font_italic)  
    #设置文字内容  
    text_fmt = cur_font.render(text, 1, color)  
    #绘制文字  
    screen.blit(text_fmt, pos)

# 开始
def show_start_info(screen):
	show_text(screen,(240, 550),'按任意键开始游戏~~~',(65, 105, 225))
	gamestart = pygame.image.load('img/gamestart.png')
	screen.blit(gamestart, (50, 30))
	pygame.display.update()

	while True:  #键盘监听事件
		for event in pygame.event.get():  # event handling loop
			if event.type == pygame.QUIT:
				sys.exit()     #终止程序
			elif event.type == pygame.KEYDOWN:
				if (event.key == pygame.K_ESCAPE):  #终止程序
					sys.exit() #终止程序
				else:
					return #结束此函数, 开始游戏

def show_gameover_info(screen):
	show_text(screen,(240, 550),'按空格键重新开始游戏~',(65, 105, 225))
	gameover = pygame.image.load('img/gameover.png')
	screen.blit(gameover, (-50, -50))
	pygame.display.update()

def main():
	# 初始化pygame
	pygame.init()  
	screen_size = (SCREEN_X,SCREEN_Y)
	# 显示窗口
	screen = pygame.display.set_mode(screen_size)
	pygame.display.set_caption(GAME_NAME)
	ball = pygame.image.load("img/Star.png")
	scores = 0
	isdead = False
	# 设置时钟
	clock = pygame.time.Clock()  
	# 蛇
	snake = Snake()
	# 食物
	food = Food()
	#欢迎信息
	show_start_info(screen)

	while True:  # 死循环确保窗口一直显示
		for event in pygame.event.get():  # 遍历所有事件
			if event.type == pygame.QUIT:  # 如果单击关闭窗口，则退出
				sys.exit()
			if event.type == pygame.KEYDOWN:
				snake.changedirection(event.key)
 				# 死后按space重新
				if event.key == pygame.K_SPACE and isdead:
					return main()
		
		# 背景颜色
		screen.fill(COLOR)
		if not isdead:
			scores+= 1
			snake.move()
		# 绘制 蛇
		for rect in snake.body:
			screen.blit(ball,rect)

		# 判断死亡
		isdead = snake.isdead();

		if isdead:
			show_gameover_info(screen)
		
		# 食物投递
		food.set()
		screen.blit(ball,food.rect)

		# 食物处理 / 吃到+50分
        # 当食物rect与蛇头重合,吃掉 -> Snake增加一个Node
		if food.rect == snake.body[0]:
			scores+=50
			food.remove()
			snake.addnode()

		# 显示分数文字
		show_text(screen,(50,500),'Scores: '+ str(len(snake.body)-5) ,(223,223,223))

		pygame.display.flip()
		clock.tick(TIME)
		
	
if __name__ == '__main__':
	main()






